import 'dart:convert';
import 'dart:io';

import 'package:awesome_dialog/awesome_dialog.dart';
import 'package:common_utils/common_utils.dart';
import 'package:convex_bottom_bar/convex_bottom_bar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:provider/provider.dart';
import 'package:taonile/config/config.dart';
import 'package:taonile/pages/product_classify.dart';
import 'package:taonile/pages/shopping_car.dart';
import 'package:taonile/tabview/home_index.dart';
import 'package:taonile/tabview/home_mine.dart';
import 'package:taonile/tabview/store_index.dart';
import 'package:taonile/views/dialog_manager.dart';
import 'package:url_launcher/url_launcher.dart';

import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../tabview/home_market.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with SingleTickerProviderStateMixin {
  List<TabItem> tabItems = [
    const TabItem(icon: Icons.local_mall_outlined, title: '商城'),
    const TabItem(icon: Icons.category_outlined, title: '分类'),
    // const TabItem(icon: Icons.store_mall_directory, title: '商圈'),
    const TabItem(icon: Icons.monetization_on_outlined, title: '交易'),
    const TabItem(icon: Icons.shopping_cart_outlined, title: '购物车'),
    const TabItem(icon: Icons.person_outline, title: '我的'),
  ];

  int _currentIndex = 0;

  HomeIndex homeIndex = const HomeIndex();
  ProductClassifyPage classifyPage = const ProductClassifyPage();

  // StoreIndex storeIndex = const StoreIndex();
  HomeMarket homeMarket = const HomeMarket();

  ShoppingCarPage shoppingCarPage = const ShoppingCarPage();
  HomeMine homeMine = const HomeMine();
  List<Widget> tabViews = [];
  late TabController tabController;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    tabViews.clear();
    tabViews.add(homeIndex);
    tabViews.add(classifyPage);
    // tabViews.add(storeIndex);
    tabViews.add(homeMarket);
    tabViews.add(shoppingCarPage);
    tabViews.add(homeMine);
    tabController = TabController(length: tabItems.length, vsync: this);
    tabController.index = _currentIndex;
    getAppVersion();
  }

  //获取APP的版本信息，兼容Android和iOS
  //String url='https://sfh.oss-cn-hangzhou.aliyuncs.com/uploads/taonile2.0.0.apk';
  getAppVersion() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    String appName = packageInfo.appName;
    String packageName = packageInfo.packageName;
    String version = packageInfo.version;
    String buildNumber = packageInfo.buildNumber;
    LogUtil.v(appName, tag: 'App的名称=');
    LogUtil.v(packageName, tag: 'App包名=');
    LogUtil.v(version, tag: 'App的版本=');

    dynamic result = await Api.checkVersion({'version': version});
    var jsonResult = jsonDecode(jsonEncode(result));
    if (jsonResult['code'] == 1) {
      String url;
      if (Platform.isAndroid) {
        url = jsonResult['data']['url'];
      } else if (Platform.isIOS) {
        url = jsonResult['data']['ios_url'];
      } else {
        return;
      }
      _alertDialog(url);
    }
  }

  _alertDialog(String url) {
    DialogManager.appUpdateDialog(context, '温馨提示', '发现新版本，是否立即升级?', () {
      launchUrl(Uri.parse(url), mode: LaunchMode.externalApplication);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // body: tabViews[_currentIndex],

      body: IndexedStack(
        index: _currentIndex,
        children: tabViews,
      ),

      bottomNavigationBar: ConvexAppBar(
        items: tabItems,
        backgroundColor: Config.colorWhite,
        color: Config.colorText2,
        activeColor: Config.colorMain,
        style: TabStyle.react,
        controller: tabController,
        elevation: 5.w,
        top: -16,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
            if (_currentIndex == tabViews.length - 1) {
              homeMine.getUserInfo((UserInfoEntity infoEntity) {
                Provider.of<UserInfoProvider>(context, listen: false).changeUserinfo(infoEntity);
              });
            }
            // if (_currentIndex == tabViews.length - 2) {
            //   SingletonManager.instance.eventBus.fire(ShoppingCarUp());
            // }
          });
        },
      ),
    );
  }
}
